var express = require('express');
var router = express.Router();
var logger = require('../common/logger').logger.getLogger("user");
var mysql_query = require('../common/mysql');
var httpresult = require('../common/response');
var md5 = require('md5');
var vertoken = require('../common/token');
var question_model = require('../models/question');
var utils = require('../common/utils')
var bank_question = require('../models/bank_question');
var bank_model = require('../models/bank');

function unique(arr, attr) {
    const res = new Map();
    return arr.filter((item) => {
        let attr_item = item[attr];
        return !res.has(attr_item) && res.set(attr_item, 1)
    })
}

router.post('/list', async function(req, res, next) {
    var sql = "select question.question_id, question.description, question.stem, question.analysis, question.answer, question.type, question.count, " +
        "chapter.name as chapter, bank.name as bank, bank_question.order_number as order_number, bank_question.bank_id as bank_id, " +
        "bank_question.score as score, bank.course_id as course_id, question.chapter_id as chapter_id from bank_question " +
        "left join question on bank_question.question_id = question.question_id " +
        "left join bank on bank_question.bank_id = bank.bank_id " +
        "left join chapter on question.chapter_id = chapter.chapter_id " +
        "where bank_question.bank_id in (?)";
    var where_params = req.body.bank_ids;
    var [error, data] = await bank_question.get_questions(sql, [where_params]);
    if (error) {
        logger.warn(error);
        return res.send(httpresult.sys_error(error));
    }
    // for test
    // for(let i = 0; i < 1000; ++ i) {
    //     data.push(data[0]);
    // }
    return res.send(httpresult.success(data));
});

router.post('/add_with_create', async function(req, res, next) {
    let [error, data] = await bank_model.get(req.body.bank_id);
    if (error) {
        logger.warn(error);
        return res.send(httpresult.sys_error(error));
    }
    if (data.length === 0) {
        return res.send(httpresult.trans_error("BANK_NOT_EXIST", "相关的题库不存在"));
    }

    let new_order_number = req.body.order_number;
    if (req.body.order_number === "") {
        let [error, data] = await mysql_query("select count(*) from bank_question where bank_id = ?", [req.body.bank_id]);
        if (error) {
            logger.warn(error);
            return res.send(httpresult.sys_error(error));
        }
        new_order_number = data[0]['count(*)'] + 1;
    }
    else {
        let [error, data] = await mysql_query("update bank_question set order_number = order_number + 1 where bank_id = ? and order_number >= ? ", [req.body.bank_id, req.body.order_number])
        if (error) {
            logger.warn(error);
            return res.send(httpresult.sys_error(error));
        }
    }
    [error, data] = await question_model.createQuestion(req.body.course_id, req.body.description, req.body.stem, req.body.analysis, req.body.answer, req.body.type, req.body.chapter_id, req.body.bank_id, req.body.count || 1);
    if (error) {
        logger.warn(error);
        return res.send(httpresult.sys_error(error));
    }
    insert_id = data;
    [error, data] = await mysql_query("insert into bank_question (bank_id, question_id, order_number, score) value (?,?,?,?)",
        [req.body.bank_id, insert_id, new_order_number, req.body.score || 1]);
    if (error) {
        logger.warn(error);
        return res.send(httpresult.sys_error(error));
    }
    return res.send(httpresult.success(req.body));
});

// {
//     bank_id: ""
//     questions: [{
//         question_id: ""
//     }]
// }
router.post('/add_batch', async function(req, res, next) {
    var [error, data] = await mysql_query("select count(*) from bank_question where bank_id = ?", [req.body.bank_id]);
    if (error) {
        logger.warn(error);
        return res.send(httpresult.sys_error(error));
    }
    let new_order_number = data[0]['count(*)'] + 1;
    let questions = req.body.questions;
    let bank_id = req.body.bank_id;

    let sql = "insert into bank_question (bank_id, question_id, order_number, score) values ? on duplicate key update score = values(score)";
    let where_params = [];
    for (let index in questions) {
        where_params.push([bank_id, questions[index].question_id, new_order_number ++, req.body.score || 1]);
    }

    [error, data] = await mysql_query(sql, [where_params]);
    if (error) {
        logger.warn(error);
        return res.send(httpresult.sys_error(error));
    }
    return res.send(httpresult.success(req.body));
});

router.post('/delete_with_destroy', async function(req, res, next) {
    let [error, data] = await bank_model.get(req.body.bank_id);
    if (error) {
        logger.warn(error);
        return res.send(httpresult.sys_error(error));
    }
    if (data.length === 0) {
        return res.send(httpresult.trans_error("BANK_NOT_EXIST", "相关的题库不存在"));
    }

    [error, data] = await question_model.destroy_question(req.body.question_id);
    if (error) {
        logger.warn(error);
        return res.send(httpresult.sys_error(error));
    }

    [error, data] = await mysql_query("delete from bank_question where question_id = ?", [req.body.question_id]);
    if (error) {
        logger.warn(error);
        return res.send(httpresult.sys_error(error));
    }

    [error, data] = await mysql_query("update bank_question set order_number = order_number - 1 where bank_id = ? and order_number > ? ", [req.body.bank_id, req.body.order_number]);
    if (error) {
        logger.warn(error);
        return res.send(httpresult.sys_error(error));
    }
    var result = data;
    return res.send(httpresult.success(result));
});

router.post('/delete', async function(req, res, next) {
    let [error, data] = await bank_model.get(req.body.bank_id);
    if (error) {
        logger.warn(error);
        return res.send(httpresult.sys_error(error));
    }
    if (data.length === 0) {
        return res.send(httpresult.trans_error("BANK_NOT_EXIST", "相关的题库不存在"));
    }

    [error, data] = await mysql_query("delete from bank_question where question_id = ? and bank_id = ? ", [req.body.question_id, req.body.bank_id]);
    if (error) {
        logger.warn(error);
        return res.send(httpresult.sys_error(error));
    }

    [error, data] = await mysql_query("update bank_question set order_number = order_number - 1 where bank_id = ? and order_number > ? ", [req.body.bank_id, req.body.order_number]);
    if (error) {
        logger.warn(error);
        return res.send(httpresult.sys_error(error));
    }
    var result = data;
    return res.send(httpresult.success(result));
});

router.post('/sort', async function(req, res, next) {
    var bank_id = req.body.bank_id;
    var sql = "update bank_question set order_number = case question_id ";
    var where_params = [];
    var in_ids = [];
    for (let question_id in req.body.data) {
        sql += " when ? then ? "
        where_params.push(Number(question_id));
        where_params.push(req.body.data[question_id]);
        in_ids.push(Number(question_id));
    }
    where_params.push(in_ids);
    sql += " end where question_id in (?)";
    var [error, data] = await mysql_query(sql, where_params);
    if (error) {
        logger.warn(error);
        return res.send(httpresult.sys_error(error));
    }
    var result = data;
    return res.send(httpresult.success(result));
});

router.post('/except', async function(req, res, next) {
    var sql = "select question.question_id, question.description, question.stem, question.analysis, question.answer, " +
        "chapter.name as chapter, bank.name as bank, bank_question.order_number as order_number, bank_question.bank_id as bank_id, " +
        "bank_question.score as score, bank.course_id as course_id, question.chapter_id as chapter_id from bank_question " +
        "left join question on bank_question.question_id = question.question_id " +
        "left join bank on bank_question.bank_id = bank.bank_id " +
        "left join chapter on question.chapter_id = chapter.chapter_id " +
        "where bank_question.question_id in (?) and bank_question.question_id not in (select bank_question.question_id from bank_question where bank_question.bank_id in (?))";
    var question_ids = req.body.question_ids;
    var bank_ids = req.body.bank_ids;
    if (!question_ids || question_ids.length === 0) {
        return res.send(httpresult.success([]));
    }
    var [error, questions] = await bank_question.get_questions(sql, [question_ids, bank_ids]);
    if (error) {
        logger.warn(error);
        return res.send(httpresult.sys_error(error));
    }
    return res.send(httpresult.success(questions));
});

router.post('/union', async function(req, res, next) {
    var sql = "select question.question_id, question.description, question.stem, question.analysis, question.answer, " +
        "chapter.name as chapter, bank.name as bank, bank_question.order_number as order_number, bank_question.bank_id as bank_id, " +
        "bank_question.score as score, bank.course_id as course_id, question.chapter_id as chapter_id from bank_question " +
        "left join question on bank_question.question_id = question.question_id " +
        "left join bank on bank_question.bank_id = bank.bank_id " +
        "left join chapter on question.chapter_id = chapter.chapter_id " +
        "where bank_question.question_id in (?) or bank_question.question_id in (select bank_question.question_id from bank_question where bank_question.bank_id in (?))";
    var question_ids = req.body.question_ids;
    var bank_ids = req.body.bank_ids;
    if (!question_ids || question_ids.length === 0) {
        return res.send(httpresult.success([]));
    }
    var [error, questions] = await bank_question.get_questions(sql, [question_ids, bank_ids]);
    if (error) {
        logger.warn(error);
        return res.send(httpresult.sys_error(error));
    }
    return res.send(httpresult.success(questions));
});

router.post('/intersect', async function(req, res, next) {
    var sql = "select question.question_id, question.description, question.stem, question.analysis, question.answer, " +
        "chapter.name as chapter, bank.name as bank, bank_question.order_number as order_number, bank_question.bank_id as bank_id, " +
        "bank_question.score as score, bank.course_id as course_id, question.chapter_id as chapter_id from bank_question " +
        "left join question on bank_question.question_id = question.question_id " +
        "left join bank on bank_question.bank_id = bank.bank_id " +
        "left join chapter on question.chapter_id = chapter.chapter_id " +
        "where bank_question.question_id in (?) and bank_question.question_id in (select bank_question.question_id from bank_question where bank_question.bank_id in (?))";
    var question_ids = req.body.question_ids;
    var bank_ids = req.body.bank_ids;
    if (!question_ids || question_ids.length === 0) {
        return res.send(httpresult.success([]));
    }
    var [error, questions] = await bank_question.get_questions(sql, [question_ids, bank_ids]);
    if (error) {
        logger.warn(error);
        return res.send(httpresult.sys_error(error));
    }
    return res.send(httpresult.success(questions));
});

module.exports = router;
